package com.wave2.shadow.testJavaGolfAssocation;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import com.wave2.shadow.controller.JGAController;
import com.wave2.shadow.persistence.Contacts;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
  "context.xml",
  "classpath:/com/wave2/shadow/hsqldb/hsqldb-context.xml"
})
@TransactionConfiguration(transactionManager="transactionManager")
@Transactional
public class testEmbeddedDB{

	@Autowired
	private JGAController jgacontroller;
	
	@Autowired
	private SessionFactory sessionFactory;
	
	//@Autowired
	//private HibernateTransactionManager transactionManager;	
	
	
	@Test
	public void testContextLoaded() {
		//insert a mockito mock for JGAController here?
		
		//Make sure the beans are autowired in.
		assertTrue(jgacontroller != null);
		assertTrue(sessionFactory != null);
	}
	
	@Test
	public void testContacts(){
		 Session sess = null;
			
			try{
	    		sess =  sessionFactory.getCurrentSession();        		
				
				Contacts user = new Contacts();
				user.setEmail("UNIT@Hibernate.test");
				user.setFirstname("Unit");
				user.setLastname("test");
				user.setPhone1("111.222.3333");
				user.setPass("somepasswordhere");
				
				sess.save(user);			
				//tx.commit();
				
				//TODO: Assert that the DB has the identical entry as above.
				Query q = sess.createQuery("FROM Contacts");
				
				List<Contacts> lst = q.list();
				
				Contacts person;
				
	            if (lst != null & ! lst.isEmpty()){
	            	person = (Contacts) lst.get(0);  
	            }
	            else{
	            	person = null;
	            }			
				
	            //do assert
				assertTrue(person != null);
				assertEquals(person.getEmail(), user.getEmail());
				assertEquals(person.getFirstname(), user.getFirstname());
				assertEquals(person.getEmail(), user.getEmail());
				assertEquals(person.getEmail(), user.getEmail());
				assertEquals(person.getEmail(), user.getEmail());
				
				System.err.println(person.toString());
			}
			catch (Exception e){
				e.printStackTrace(System.err);
				fail ("Exception encountered! Transaction rolled back.\n" + e.getMessage());
			}
	}
	
}
